/**
 * @file adminAuthSlice.js
 * @description 后台管理系统的管理员认证状态 Redux slice
 */
import { createSlice } from '@reduxjs/toolkit';

const getInitialAdminAuthState = () => {
  try {
    const storedAdmin = localStorage.getItem('adminUser');
    if (storedAdmin) {
      return { isAuthenticated: true, admin: JSON.parse(storedAdmin) };
    }
  } catch (error) {
    console.error("无法从localStorage解析管理员数据:", error);
  }
  return { isAuthenticated: false, admin: null };
};

const initialState = getInitialAdminAuthState();

const adminAuthSlice = createSlice({
  name: 'adminAuth',
  initialState,
  reducers: {
    /**
     * 管理员登录成功
     * @param {object} state - 当前的 state
     * @param {object} action - Redux action，action.payload 应该是管理员信息对象
     */
    adminLoginSuccess: (state, action) => {
      state.isAuthenticated = true;
      state.admin = action.payload;
      try {
        localStorage.setItem('adminUser', JSON.stringify(action.payload));
      } catch (error) {
        console.error("无法向localStorage存储管理员数据:", error);
      }
    },
    /**
     * 管理员登出
     * @param {object} state - 当前的 state
     */
    adminLogout: (state) => {
      state.isAuthenticated = false;
      state.admin = null;
      try {
        localStorage.removeItem('adminUser');
      } catch (error) {
        console.error("无法从localStorage移除管理员数据:", error);
      }
    },
  },
});

export const { adminLoginSuccess, adminLogout } = adminAuthSlice.actions;
export default adminAuthSlice.reducer;